package dream

import (
	"bufio"
	"bytes"
	"fmt"
	"os"
	"runtime"
	"strconv"
	"strings"
	"time"
)

func GoID() uint64 {
	b := make([]byte, 64)
	b = b[:runtime.Stack(b, false)]
	b = bytes.TrimPrefix(b, []byte("goroutine "))
	b = b[:bytes.IndexByte(b, ' ')]
	n, _ := strconv.ParseUint(string(b), 10, 64)
	return n
}

func CrashSnap(err interface{}) {
	if err != nil {
		sPath := workPath
		sPath += AppName() + "." + time.Now().Format("20060102.150405.crash.txt")
		f, err1 := os.Create(sPath)
		if err1 == nil {
			w := bufio.NewWriter(f) //创建新的 Writer 对象

			var ser = fmt.Sprint(err)
			fmt.Println(ser) // 这里的err其实就是panic传入的内容
			w.WriteString(ser)

			buf := make([]byte, 1<<16)
			nl := runtime.Stack(buf, false)
			bufs := buf[0:nl]
			ss := string(bufs)
			n1 := strings.Index(ss, "panic(")
			if n1 >= 0 {
				var ss0 string
				n0 := strings.Index(ss, ":\n")
				if n0 > 0 {
					ss0 = ss[0 : n0+2]
				}
				ss1 := ss[n1:]
				n1 = strings.Index(ss1, "runtime/panic.go")
				if n1 >= 0 {
					ss1 = ss1[n1+len("runtime/panic.go"):]
					n1 = strings.Index(ss1, "\n")
					if n1 >= 0 {
						ss = ss1[n1+1:]
						ss = ss0 + ss
					}
				}
			}
			fmt.Println(ss)
			w.WriteString("\r\n")
			w.WriteString(ss)

			fmt.Println("ALL")
			w.WriteString("\r\n")
			w.WriteString("ALL")
			nl = runtime.Stack(buf, true)
			buf = buf[0:nl]
			fmt.Println(string(buf))
			w.WriteString("\r\n")
			w.WriteString(string(buf))

			w.Flush()
			f.Close()
		}
		panic(err)
	}
}
